package com.kele.demo.controller;

import com.kele.demo.annotation.AuthToken;
import com.kele.demo.dto.RegisterDTO;
import com.kele.demo.entity.LoginUser;
import com.kele.demo.service.impl.LoginUserServiceImpl;
import com.kele.utils.RequestResult;
import com.kele.utils.RequestResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chunhui.li
 * @date 2022/2/15 9:49
 * @Description
 * @ClassName LoginController
 */
@RestController
@RequestMapping("/login")
@Slf4j
//@CrossOrigin(origins = "*")
public class LoginController {

    @Autowired
    LoginUserServiceImpl loginUserService;


    @PostMapping("/getAuth")
    public RequestResult login(@RequestBody LoginUser loginUser){
        log.info("==============================> {}",loginUser.toString());
        Map<String, String> tokenMap = new HashMap<>();
        LoginUser user = loginUserService.getUser(loginUser);
        if (user!=null){
            tokenMap.put("token",user.getToken());
            return RequestResultUtil.success(tokenMap);
        }
        return RequestResultUtil.error(-1,"用户名或密码错误");
    }

    @PostMapping("/register")
    public RequestResult register(@RequestBody RegisterDTO registerDTO) {
        log.info("注册的入参",registerDTO.toString());
        int result = loginUserService.registerUser(registerDTO);
        if (result>0){
            return RequestResultUtil.success();
        }
        return RequestResultUtil.error(-1,"注册失败");
    }


    /**
     * 用来校验token
     * @return
     */
//    @AuthToken
    @GetMapping("/checkToken")
    public Boolean checkToken( @RequestParam String token){

//        String token = request.getHeader("token");
        log.info("token ===========> {}",token);
        Boolean result = loginUserService.checkToken(token);
        if (result){
            return true;
        }
        return false;

    }

}
